package tuling.netty.quickstart;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

/**
 * @author RenGaoshuai
 * @date 2023/11/30 11:12
 * @description
 */
public class QuickStartClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 连接建立后调用该方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //像通道中写入数据
        ByteBuf byteBuf = Unpooled.copiedBuffer("HelloServer,I`m client", CharsetUtil.UTF_8);
        ctx.writeAndFlush(byteBuf);
    }

    /***
     * 读取通道中的数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buffer = (ByteBuf) msg;
        String s = buffer.toString(StandardCharsets.UTF_8);
        System.out.println("客户端接收到服务端发送的消息："+s);
    }
}
